package com.canyou.jackson;

import com.canyou.constants.CommonConstants;
import com.canyou.utils.StringUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 金额反序列化
 *
 * @author fy
 * @date 20/03/20 16:02
 */
@JsonComponent
public class MoneyDeserializer extends StdDeserializer<Money> {

    private static final String CURRENCY_UNIT = CommonConstants.CURRENCY_UNIT;

    protected MoneyDeserializer() {
        super(Money.class);
    }

    @Override
    public Money deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String value = p.getValueAsString();
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return Money.of(CurrencyUnit.of(CURRENCY_UNIT), new BigDecimal(value), RoundingMode.HALF_UP);
    }

}
